package com.rzjm.api.netty.water.business.inhandler;

import cn.hutool.json.JSONUtil;
import com.rzjm.api.netty.water.entity.Receive3Data;
import com.rzjm.api.netty.water.entity.ReceiveData;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

import static com.rzjm.api.netty.water.constant.ReceiveTypeEnum.*;

/**
 * @author WangWT
 * @Description: 分发数据到指定处理器
 * @date 2023/4/14 9:50
 */
@Component
public class DispatchHandler {
    private static final Logger LOGGER = LoggerFactory.getLogger(DispatchHandler.class);

    private Map<Integer, InHandler> handlers = new HashMap<>();
    @Autowired
    private Receive0InHandler receive0InHandler;
    @Autowired
    private Receive1InHandler receive1InHandler;
    @Autowired
    private Receive2InHandler receive2InHandler;
    @Autowired
    private Receive3InHandler receive3InHandler;
    @Autowired
    private Receive4InHandler receive4InHandler;
    @Autowired
    private Receive5InHandler receive5InHandler;
    @Autowired
    private Receive9InHandler receive9InHandler;
    @Autowired
    private Receive11InHandler receive11InHandler;
    @Autowired
    private Receive45InHandler receive45InHandler;
    @Autowired
    private ReceiveCommonInHandler receiveCommonInHandler;

    public void dispatchMsg(ChannelHandlerContext ctx, String message) {
        ReceiveData receiveData = JSONUtil.toBean(message, ReceiveData.class);
        int type = receiveData.getType();
        //根据type获取处理器
        InHandler inHandler = handlers.get(type);
        if(inHandler != null){
			if (type == RECEIVE_TYPE_3.getType()){
				receiveData = JSONUtil.toBean(message, Receive3Data.class);
			}
            inHandler.handler(ctx, receiveData);
        }else {
            //通用处理器
            receiveCommonInHandler.handler(ctx, receiveData);
        }
    }

    @PostConstruct
    private void init() {
        handlers.put(RECEIVE_TYPE_0.getType(), receive0InHandler);
        handlers.put(RECEIVE_TYPE_1.getType(), receive1InHandler);
        handlers.put(RECEIVE_TYPE_2.getType(), receive2InHandler);
        handlers.put(RECEIVE_TYPE_3.getType(), receive3InHandler);
        handlers.put(RECEIVE_TYPE_4.getType(), receive4InHandler);
        handlers.put(RECEIVE_TYPE_5.getType(), receive5InHandler);
        handlers.put(RECEIVE_TYPE_9.getType(), receive9InHandler);
        handlers.put(RECEIVE_TYPE_11.getType(), receive11InHandler);
        handlers.put(RECEIVE_TYPE_45.getType(), receive45InHandler);
    }
}
